//
//  HKWebViewController+JSBridge.m
//  YNDemo
//
//  Created by 胡锦涛 on 2020/11/12.
//

#import "HKWebViewController+JSBridge.h"
#import "HKTool.h"
#import <HKLibBase/HKLibBaseHeader.h>
#import <QuartzCore/QuartzCore.h>
#import <QuartzCore/CoreAnimation.h>
#import <MobileCoreServices/UTCoreTypes.h>
@implementation HKWebViewController (JSBridge)

- (NSString *) testSyn: (NSString *) msg
{
    return [msg stringByAppendingString:@"[ syn call]"];
}

- (void) testAsyn:(NSString *) msg :(JSCallback) completionHandler
{
    completionHandler([msg stringByAppendingString:@" [ asyn call]"],YES);
}
// 进入二维码扫描页面
- (void) callQRCode:(NSDictionary *) args :(JSCallback)completionHandler
{
//    [HKTool openViewController:self moreLink:@"yunniao://qrcode"];
    
}
// 进入地图页面
- (void) callNativeMap:(NSDictionary *) args :(JSCallback)completionHandler
{
//    [HKTool openViewController:self moreLink:@"yunniao://map"];
}
// 支持动态跳转Native页面
-(void)callNativeLink:(NSString *)link :(JSCallback)completionHandler {
    dispatch_async(dispatch_get_main_queue(), ^{
//        [HKTool openViewController:self moreLink:link];
    });
}
// 打开二级页面
-(void)openUrlByClient:(NSString *)url :(JSCallback)completionHandler {
    NSLog(@"二级界面跳转 url:%@",url);
//    [HKTool openViewController:self moreLink:url];
}
// 分享
-(void)shareByClient:(NSString *)shareInfo :(JSCallback)completionHandler {
//    [YNLibShareTool shareToWeiXinWithText:@""];
}

// 支付
-(void)appPay:(NSString *)payInfo :(JSCallback)completionHandler {
//    NSString *res = [YNLibShareTool sendWeiXinPay:^{
//
//    }];
//    if( ![@"" isEqual:res] ){
//        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"支付失败" message:res delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//
//        [alter show];
//    }
}
// 拨打电话
-(void)callPhone:(NSString *)phone :(JSCallback)completionHandler {
//    if (phone && phone.length > 0) {
//        [HKTool callPhone:phone];
//    }
}
// 修改密码
-(void)modifyPassword:(NSString *)password :(JSCallback)completionHandler {
    //modifyPassword
//    [HKTool openViewController:self moreLink:@"yunniao://modifyPassword"];
}
// 反馈
-(void)feedBackEvent:(NSString *)params :(JSCallback)completionHandler {
//    [HKTool openViewController:self moreLink:@"yunniao://feedBack"];
}
// 协议
-(void)procotolEvent:(NSString *)params :(JSCallback)completionHandler {
//    [HKTool openViewController:self moreLink:@"yunniao://privacy"];
}
// 清除缓存
-(void)clearAppCache:(NSString *)params :(JSCallback)completionHandler {
//    [QMUITips showLoading:@"正在清除缓存..." inView:HKKeyWindow hideAfterDelay:0.5];
//    [HKTool removeDiskCache];
//    [HKTool clearAllCache];
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        //执行其他清除操作
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [QMUITips showWithText:@"清除缓存成功"];
//        });
//    });
}
// 关闭页面
-(void)back{
    [self hk_back];
}
// 返回根视图
-(void)backToRootPage:(NSDictionary *) args :(JSCallback)completionHandler{
    [self hk_dismissToRoot];
}
// 调用相册
-(void)chooseImage:(NSString*)image :(JSCallback)completionHandler {
    
    self.successMethod = image;
    NSLog(@"successMethod %@",self.successMethod);
    UIActionSheet *alert = [[UIActionSheet alloc]initWithTitle:@"请选择图片来源" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从手机相册选择", nil];
    [alert showInView:self.view];
}

#pragma mark ----UIActionSheet------

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex==0)
        [self shootPiicturePrVideo];
    else if(buttonIndex==1)
        [self selectExistingPictureOrVideo];
}
#pragma  mark- 拍照模块
//从相机上选择
-(void)shootPiicturePrVideo{
    [self getMediaFromSource:UIImagePickerControllerSourceTypeCamera];
}
//从相册中选择
-(void)selectExistingPictureOrVideo{
    [self getMediaFromSource:UIImagePickerControllerSourceTypePhotoLibrary];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    self.lastChosenMediaType=[info objectForKey:UIImagePickerControllerMediaType];
    if([self.lastChosenMediaType isEqual:(NSString *) kUTTypeImage])
    {
        UIImage *chosenImage=[info objectForKey:UIImagePickerControllerEditedImage];//
        NSString *method =[NSString stringWithFormat:@"data:image/png;base64,%@", [self getBase64ImageStringWithData:UIImageJPEGRepresentation(chosenImage, 0.5)]];
//        @""
        [self.webView callHandler:self.successMethod arguments:@[method] completionHandler:^(id  _Nullable value) {
            NSLog(@"图片选择了.....: %@",value);
        }];
    }
    if([self.lastChosenMediaType isEqual:(NSString *) kUTTypeMovie])
    {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示信息!" message:@"系统只支持图片格式" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil];
        [alert show];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)getMediaFromSource:(UIImagePickerControllerSourceType)sourceType
{
    NSArray *mediatypes=[UIImagePickerController availableMediaTypesForSourceType:sourceType];
    if([UIImagePickerController isSourceTypeAvailable:sourceType] &&[mediatypes count]>0){
        NSArray *mediatypes=[UIImagePickerController availableMediaTypesForSourceType:sourceType];
        UIImagePickerController *picker=[[UIImagePickerController alloc] init];
        picker.mediaTypes=mediatypes;
        picker.delegate=self;
        picker.allowsEditing=YES;
        picker.sourceType=sourceType;
        NSString *requiredmediatype=(NSString *) kUTTypeImage;
        NSArray *arrmediatypes=[NSArray arrayWithObject:requiredmediatype];
        [picker setMediaTypes:arrmediatypes];
        picker.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:picker animated:YES completion:nil];
    }
    else{
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"错误信息!" message:@"当前设备不支持拍摄功能" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil];
        [alert show];
    }
}
static UIImage *shrinkImage(UIImage *orignal,CGSize size)
{
    CGFloat scale=[UIScreen mainScreen].scale;
    CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB();
    CGContextRef context=CGBitmapContextCreate(NULL, size.width *scale,size.height*scale, 8, 0, colorSpace, kCGImageAlphaPremultipliedFirst);
    CGContextDrawImage(context, CGRectMake(0, 0, size.width*scale, size.height*scale), orignal.CGImage);
    CGImageRef shrunken=CGBitmapContextCreateImage(context);
    UIImage *final=[UIImage imageWithCGImage:shrunken];
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    CGImageRelease(shrunken);
    return  final;
}

-(NSString *)getBase64ImageStringWithData:(NSData *)data{
    return  [data base64Encoding];
}
@end
